const express = require("express");
const path = require("path");
const router = express.Router();
const multer = require("multer");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, "../../public/upload"));
  },
  filename: function (req, file, cb) {
    const timeStamp = Date.now();
    const randomStr = Math.random().toString(36).slice(-6);
    const ext = path.extname(file.originalname);
    const filename = `${timeStamp}-${randomStr}${ext}`;
    cb(null, filename);
  },
});
const upload = multer({
  storage,
  limits: {
    fileSize: 2 * 1024 * 1024,
  },
  fileFilter(req,file,cb){
      const extname = path.extname(file.originalname)
      const whiteList = [".jpg",".png",".jpeg"]
      if(whiteList.includes(extname)){
          cb(null,true)
      }else{
          cb(new Error('your ext name is not support'))
      }
  }
});

router.post("/", upload.single("img"), (req, res) => {
    const url = `/upload/${req.file.filename}`
    res.send({
        code:200,
        msg:'上传图片成功',
        data:url
    })
});

module.exports = router;
